package com.ze.sys.db.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.ze.sys.dao.SysUserBackDao;
import com.ze.sys.dao.SysUserDao;
import com.ze.sys.db.AbstractBackUpDataHandler;
import com.ze.sys.db.BackUpDataSceneEnum;
import com.ze.sys.db.rule.SysUserBackUpDataRule;
import com.ze.sys.entity.SysUser;
import com.ze.sys.entity.po.SysUserPo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据归档具体流程
 */
@Slf4j
@Component
public class SysUserForwardHandler extends AbstractBackUpDataHandler<SysUser, SysUserBackUpDataRule> {

    /**
     * 归档规则，可以配合 nacos动态配置
     * (设置为String格式的json，与SysUserBackUpDataRule中的参数一一对应)
     */
    @Value("${backUpDataScene.sysUserBackupRuleStr}")
    private String sysUserBackupRuleStr;

    /**
     * 归档停止flag，配合nacos
     * (可以随时停止归档)
     */
    @Value("${backUpDataScene.stopFlag}")
    private Boolean stopFlag;

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private SysUserBackDao sysUserBackDao;

    @Override
    public Boolean needStop() {
        return stopFlag;
    }

    @Override
    public BackUpDataSceneEnum getScene() {
        return BackUpDataSceneEnum.USER_FORWARD;
    }

    @Override
    public List<SysUser> queryData(SysUserBackUpDataRule rule) {
        SysUserPo sysUser = new SysUserPo();
        List<SysUser> sysUserList = sysUserDao.queryAllByLimit(sysUser, rule.getBeginId(), rule.getEndId());
        return sysUserList;
    }

    @Override
    public void insertData(List<SysUser> sysUserList) {
        sysUserBackDao.insertBatchNoId(sysUserList);
    }

    @Override
    public void deleteData(List<SysUser> dataList) {
        List<Long> ids = dataList.stream().map(SysUser::getId).collect(Collectors.toList());
        sysUserDao.batchDelete(ids);
    }

    @Override
    public SysUserBackUpDataRule getRule() {
        SysUserBackUpDataRule backUpRule = JSON.parseObject(sysUserBackupRuleStr, SysUserBackUpDataRule.class);
        Preconditions.checkNotNull(backUpRule, "归档规则不能为空！");
        Preconditions.checkNotNull(backUpRule.getQuerySize(), "查询数量不能为空！");
        Preconditions.checkNotNull(backUpRule.getBeginId(), "beginId不能为空！");
        Long endId = backUpRule.getBeginId() + backUpRule.getQuerySize();
        backUpRule.setEndId(endId);
        return backUpRule;
    }

    @Override
    public SysUserBackUpDataRule changeOffSet(SysUserBackUpDataRule backupDataRule) {
        backupDataRule.setEndId(backupDataRule.getEndId());
        Long beginId = backupDataRule.getBeginId() + backupDataRule.getQuerySize();
        backupDataRule.setBeginId(beginId);
        return backupDataRule;
    }

}